package com.back.Service.impl;

import com.back.Dao.User;
import com.back.Mapper.UserMapper;
import com.back.Service.UserService;
import com.back.Utils.TokenUtils;
import com.back.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    public Integer DelUser(int id) {
        return userMapper.DelUser(id);
    }

    @Override
    public Integer addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    public Integer updateUser(User user) {
        userMapper.deleteToken(user.getId());
        return userMapper.updateUser(user);
    }
    //验证用户账号是否合法
    public User login(User user){
        //根据用户名查询数据库的用户信息
        User dbUser = userMapper.selectByUserName(user.getUserName());
        if(dbUser == null){
            //数据库无该用户抛出异常
            throw new ServiceException("用户名或密码错误");
        }
        if(!user.getUserPwd().equals(dbUser.getUserPwd())) {
            throw new ServiceException("用户名或密码错误");
        }
        //生成token
        String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getUserPwd());
        userMapper.updateToken(dbUser.getId(), token);
        dbUser.setToken(token);
        return dbUser;
    };
    public User register(User user) {
        User dbUser = userMapper.selectByUserName(user.getUserName());
        if (dbUser != null) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户名已存在");
        }
        user.setUserName(user.getUserName());
        userMapper.insert(user);
        return user;
    }
}
